package com.xishu.task;

import com.xishu.bo.SendCount;
import com.xishu.bo.response.Report;
import com.xishu.client.EmailClient;
import com.xishu.config.Config;
import com.xishu.config.Constant;
import com.xishu.dao.jpa.SendHistoryDao;
import com.xishu.entity.Company;
import com.xishu.entity.customer.*;
import com.xishu.entity.plat.GlobalSetting;
import com.xishu.service.*;
import com.xishu.util.*;
import org.apache.logging.log4j.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.persistence.Tuple;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Component
public class ZeroTimeSystemTask implements Tools {
    private static Logger logger = LoggerFactory.getLogger(ZeroTimeSystemTask.class);
    private CommonService commonService = CommonService.getInstance();
    private CustomerService customerService = CustomerService.getInstance();
    private  GlobalService globalService = GlobalService.getInstance();
    private CustomerTaskService customerTaskService = CustomerTaskService.getInstance();
    private Config config = Config.getInstance();
    public static String UNPLANNED_EMAIL_TITLE = "[DoLA] You are running low on credits for verification services 您的驗證碼配額不足";
    public static String PLAN_EMAIL_TITLE = "[DoLA] You are running low on credits for marketing您的營銷配額不足";





    /**
     * 每1分钟定时执行一次,
     * <p>
     * 一分钟后再校验
     *
     * @throws Exception
     */
    @Scheduled(initialDelay = 60 * 1000, fixedDelay = 1 * 60 * 1000)
    public void action() throws Exception {
        if (config.isWindows()) {
            return;
        }

        LeaderService leaderService = LeaderService.getInstance();
        if (!leaderService.elect()) {
            logger.info("elect failed");
            return;
        }

        ThreadContext.put(Constant.REQUEST_ID, "zero time system task");

        logger.info("will do the ZeroTimeSystemTask");

        dealVipUser();
        vipLevelTicketTask();
        checkQuota();
    }

    /**
     * 处理VIP用户
     */
    private void dealVipUser() {
        if (!TaskUtil.vipUserTaskExecuteTime()) {
            logger.info("current time is not the task execute time");
            return;
        }

        try {
            HashMap<String, Boolean> vipUserMap = GlobalSave.getInstance().getVipUserMap();
            String today = DateUtil.formatDayDate(System.currentTimeMillis());

            if (vipUserMap.get(today) != null) {
                logger.info("today vip user deal");
                return;
            }

            Customer customer = new Customer();
            customer.setVip(true);
            customer.setEndVipEndTime(System.currentTimeMillis());
            logger.info("dealVipUser");

            commonService.doAll(customer, (customerInDb) -> {
                try {
                    logger.info("deal customer name {}, id {}", customerInDb.getName(), customerInDb.getId());
                    customerInDb.setVip(false);
                    customerInDb.setVipEndTime(null);
                    commonService.save(customerInDb);
                } catch (Exception e) {
                    logger.error("e", e);
                }
            });

            //设置成已经处理
            vipUserMap.put(today, true);

        } catch (Exception e) {
            logger.error("e", e);
        }
    }

    /**
     * 会员等级模式处理,会员等级只在凌晨固定时间执行
     *
     * @throws Exception
     */
    private void vipLevelTicketTask() throws Exception {
        if (!TaskUtil.isTaskExecuteTime()) {
            logger.info("current time is not the task execute time");
            return;
        }

        try {
            HashMap<String, Boolean> vipTicketLevelMap = GlobalSave.getInstance().getVipTicketLevelMap();
            String today = DateUtil.formatDayDate(System.currentTimeMillis());

            if (vipTicketLevelMap.get(today) != null) {
                logger.info("today vip ticket level user deal");
                return;
            }

            logger.info("vipLevelTicketTask");

            commonService.doAll(new Customer(), (customer) -> {
                Long vipLevelId = customer.getVipLevelId();

                //添加普通的等级
                if (vipLevelId != null) {
                    try {
                        customerService.addLevelTicketToCustomer(vipLevelId, customer.getId());
                    } catch (Exception e) {
                        logger.error("e", e);
                    }
                }

                //添加VIP等级
                logger.info("customer {} , company {}, vip {}, vip end time {}", customer.getId(), customer.getCompanyId(), getBoolean(customer.getVip()), customer.getVipEndTime());
                if (customer.getCompanyId() != null && getBoolean(customer.getVip()) && getLong(customer.getVipEndTime()) > System.currentTimeMillis()) {
                    try {
                        VipLevel vipLevel = customerService.findVipLevel_company_vip(customer.getCompanyId());
                        customerService.addLevelTicketToCustomer(vipLevel.getId(), customer.getId());
                    } catch (Exception e) {
                        logger.error("e", e);
                    }
                }
            });

            //设置标记
            vipTicketLevelMap.put(today, true);
        } catch (Exception e) {
            logger.error("e", e);
        }
    }

    /**
     * 判断配额是否充足
     */
    private void checkQuota() {
        //非windows环境才做校验
        if (!Config.getInstance().isWindows()) {
            if (!TaskUtil.isQuotaExecuteTime()) {
                logger.info("its not the quota execute time");
                return;
            }
        }

        HashMap<String, Boolean> sendHistoryMap = GlobalSave.getInstance().getSendHistoryMap();
        String today = DateUtil.formatDayDate(System.currentTimeMillis());
        if (sendHistoryMap.get(today) != null) {
            logger.info(" history today deal");
            return;
        }

        try {
            //检查每个餐厅是否满足了发送条件
            commonService.doAll(new Company(), (company -> {
                //先检查非计划性的任务
                try {
                    //开了会员功能的店才做
                    CompanyConfig companyConfig = company.getCompanyConfig();
                    if (companyConfig == null) {
                        logger.info("can not find the company config {}", company.getId());
                        return;
                    }

                    if (!getBoolean(companyConfig.getCustomerOpen())) {
                        logger.info("the company {} do not open the customer function", company.getId());
                        return;
                    }

                    companyUnplannedCheck(company, true);
                    companyUnplannedCheck(company, false);
                    companyPlanCheck(company, true);
                    companyPlanCheck(company, false);
                } catch (Exception e) {
                    logger.error("e", e);
                }
            }));

            sendHistoryMap.put(today, true);
        } catch (Exception e) {
            logger.error("e", e);
        }
    }

    /**
     * 公司的非计划配额的计算
     *
     * @param company
     */
    private void companyUnplannedCheck(Company company, boolean email) throws Exception {
        logger.info("companyEmailUnplannedCheck task {}", email);
        NoticeHistory noticeHistory = new NoticeHistory();
        noticeHistory.setCompanyId(company.getId());
        noticeHistory.setPlan(false);
        noticeHistory.setEmail(email);
        //过去七天
        noticeHistory.setStartCreateTime(System.currentTimeMillis() - DateUtil.ONE_DAY * 7 - DateUtil.ONE_HOUR);
        List<NoticeHistory> noticeHistoryList = commonService.searchAll(noticeHistory);

        //判断非计划的数量
        Optional<Quota> quotaOptional = customerService.findQuotaOrCreate(company.getId());
        if (!quotaOptional.isPresent()) {
            logger.info("can not find the quota");
            return;
        }

        //判断是否开通了
        CompanyConfig companyConfig = company.getCompanyConfig();
        if (companyConfig == null) {
            logger.info("do not has the company config {}", company.getId());
            return;
        }

        if (email && !getBoolean(companyConfig.getEmailToken())) {
            logger.info("company close the email token {}", company.getId());
            return;
        }

        if (!email && !getBoolean(companyConfig.getPhoneToken())) {
            logger.info("company close the sms token {}", company.getId());
            return;
        }

        Quota quota = quotaOptional.get();
        int unPlanCanUsed = 0;

        if (email) {
            unPlanCanUsed = getInt(quota.getUnPlanEmailCanUsed());
        } else {
            unPlanCanUsed = getInt(quota.getUnPlanSmsCanUsed());
        }

        //非计划邮件已经用完了
        if (unPlanCanUsed <= 0) {
            //再判断是否已经发送了
            Optional<NoticeHistory> historyOptional = noticeHistoryList.stream().filter(p -> getBoolean(p.getUsedOut())).findAny();

            //该计划已经发送过了
            if (historyOptional.isPresent()) {
                logger.info("the out task already send for company {}", company.getId());
                return;
            }

            {
                String content = unplannedNoticeTemplate(company.getName(), email, "接下來", "ran out");
                //没有发送过，那么发送一次
                EmailClient.getInstance().sendEmail(company.getEmail(), UNPLANNED_EMAIL_TITLE, content);
            }

            //添加已经发送完成的任务
            {
                NoticeHistory noticeHistoryNew = new NoticeHistory();
                noticeHistoryNew.setCompanyId(company.getId());
                noticeHistoryNew.setPlan(false);
                noticeHistoryNew.setEmail(email);
                noticeHistoryNew.setUsedOut(true);
                commonService.directSave(noticeHistoryNew);
            }

            return;
        }

        boolean match = unplannedCheckTime(company, noticeHistoryList, quota, email, 7);

        if (match) {
            logger.info("match the 7 days");
            return;
        }

        unplannedCheckTime(company, noticeHistoryList, quota, email, 14);
    }

    /**
     * 判断多少天的量是否够用了
     *
     * @param company
     * @param noticeHistoryList
     * @param quota
     * @param time
     * @return
     * @throws Exception
     */
    private boolean unplannedCheckTime(Company company, List<NoticeHistory> noticeHistoryList, Quota quota, boolean email, int time) throws Exception {
        //判断是否不够X天的量是否够用了
        long endTimeInDay = DateUtil.endTimeInDay(System.currentTimeMillis());
        long endTime = endTimeInDay - DateUtil.ONE_DAY;
        long startTime = DateUtil.startTimeInDay(endTime - DateUtil.ONE_DAY * time);

        SendHistoryDao sendHistoryDao = BeanUtil.getBean(SendHistoryDao.class);
        List<Tuple> tupleList = sendHistoryDao.countSend(startTime, endTime, company.getId(), !email, email, false);
        List<Report> reportList = tupleList.stream().map(p -> {
            Report report = new Report();
            NativeResultProcessUtils.convertTupleToBean(p, report);
            return report;
        }).collect(Collectors.toList());

        int maxCount = 0;

        //过去没有发，那么就是10条
        if (reportList.size() == 0) {
            maxCount = 10;
        } else {
            maxCount = new Double(reportList.stream().mapToDouble(p -> getDouble(p.getValue())).max().getAsDouble()).intValue();
        }

        //用最大值乘以7天，来判断是否未来1周足够用了
        if (maxCount * time > quota.getUnPlanEmailCanUsed()) {
            Optional<NoticeHistory> historyOptional = null;
            //再判断是否已经发送了
            if (time == 7) {
                historyOptional = noticeHistoryList.stream().filter(p -> getBoolean(p.getOneWeek())).findAny();
            } else {
                historyOptional = noticeHistoryList.stream().filter(p -> getBoolean(p.getTwoWeek())).findAny();
            }

            //该计划已经发送过了
            if (historyOptional.isPresent()) {
                logger.info("the one week task already send for company {}", company.getId());
                return true;
            }

            //没有发送过，那么发送一次
            {
                if (time == 7) {
                    String content = unplannedNoticeTemplate(company.getName(), email, "接下來這周", "may be not enough for next week");
                    EmailClient.getInstance().sendEmail(company.getEmail(), UNPLANNED_EMAIL_TITLE, content);
                } else {
                    String content = unplannedNoticeTemplate(company.getName(), email, "接下來兩周", "may be not enough for next 2 weeks");
                    EmailClient.getInstance().sendEmail(company.getEmail(), UNPLANNED_EMAIL_TITLE, content);
                }
            }

            //添加已经发送完成的任务
            {
                NoticeHistory noticeHistoryNew = new NoticeHistory();
                noticeHistoryNew.setCompanyId(company.getId());
                noticeHistoryNew.setPlan(false);
                if (time == 7) {
                    noticeHistoryNew.setOneWeek(true);
                } else {
                    noticeHistoryNew.setTwoWeek(true);
                }
                noticeHistoryNew.setEmail(email);

                commonService.directSave(noticeHistoryNew);
            }

            return true;
        }

        return false;
    }

    /**
     * 检查计划配额
     *
     * @param company
     */
    private void companyPlanCheck(Company company, boolean email) throws Exception {
        logger.info("email task {}", email);
        NoticeHistory noticeHistory = new NoticeHistory();
        noticeHistory.setCompanyId(company.getId());
        noticeHistory.setPlan(true);
        noticeHistory.setEmail(email);
        //过去七天
        noticeHistory.setStartCreateTime(System.currentTimeMillis() - DateUtil.ONE_DAY * 7 - DateUtil.ONE_HOUR);
        List<NoticeHistory> noticeHistoryList = commonService.searchAll(noticeHistory);

        //判断非计划的数量
        Optional<Quota> quotaOptional = customerService.findQuotaOrCreate(company.getId());

        if (!quotaOptional.isPresent()) {
            logger.info("can not find the quota");
            return;
        }

        Quota quota = quotaOptional.get();
        int canUsed = 0;

        if (email) {
            canUsed = getInt(quota.getEmailCanUsed());
        } else {
            canUsed = getInt(quota.getSmsCanUsed());
        }

        //查询该公司下面的所有任务，需要是定时任务，并且是没有暂停的任务
        List<MarketTask> marketTaskList = customerService.findMarketTaskByCompanyId(company.getId());
        List<MarketTask> periodMarketTaskList = marketTaskList.stream().filter(p -> getBoolean(p.getPeriodTask())).filter(p -> getInt(p.getStatus()) == 0).collect(Collectors.toList());

        //过滤出需要的条数
        {
            SendCount sendCount = getSendCount(periodMarketTaskList, Arrays.asList(System.currentTimeMillis() + DateUtil.ONE_DAY));

            if (email) {
                addVipAndBirthdayEmailCount(company, sendCount, 1);
            }

            boolean isOver = false;

            if (email) {
                isOver = sendCount.getEmail() > 0 && canUsed < sendCount.getEmail();
            } else {
                isOver = sendCount.getSms() > 0 && canUsed < sendCount.getSms();
            }

            //判断是否超了
            if (isOver) {
                //判断是否已经发送过了，没有发送则发送报告
                Optional<NoticeHistory> historyOptional = null;

                if (email) {
                    historyOptional = noticeHistoryList.stream().filter(p -> getBoolean(p.getEmail()) && getBoolean(p.getNextDay())).findAny();
                } else {
                    historyOptional = noticeHistoryList.stream().filter(p -> !getBoolean(p.getEmail()) && getBoolean(p.getNextDay())).findAny();
                }

                if (historyOptional.isPresent()) {
                    logger.info("already send next day email {} notice for company {}", email, company.getId());
                } else {
                    //发送，并记录日志
                    logger.info("will create new notice template {}", company.getId());
                    String content = planNoticeTemplate(company.getName(), email, "明天", "tomorrow");
                    EmailClient.getInstance().sendEmail(company.getEmail(), PLAN_EMAIL_TITLE, content);

                    NoticeHistory noticeHistoryNew = new NoticeHistory();
                    noticeHistoryNew.setCompanyId(company.getId());
                    noticeHistoryNew.setPlan(true);
                    noticeHistoryNew.setEmail(email);
                    noticeHistoryNew.setNextDay(true);
                    commonService.directSave(noticeHistoryNew);
                }

                return;
            }
        }

        {
            SendCount sendCount = getSendCount(periodMarketTaskList, Arrays.asList(1, 2, 3, 4, 5, 6, 7).stream().map(p -> System.currentTimeMillis() + DateUtil.ONE_DAY * p).collect(Collectors.toList()));

            if (email) {
                addVipAndBirthdayEmailCount(company, sendCount, 7);
            }

            boolean isOver = false;

            if (email) {
                isOver = sendCount.getEmail() > 0 && canUsed < sendCount.getEmail();
            } else {
                isOver = sendCount.getSms() > 0 && canUsed < sendCount.getSms();
            }

            if (isOver) {
                //判断是否已经发送过了，没有发送则发送报告
                Optional<NoticeHistory> historyOptional = null;

                if (email) {
                    historyOptional = noticeHistoryList.stream().filter(p -> getBoolean(p.getEmail()) && getBoolean(p.getOneWeek())).findAny();
                } else {
                    historyOptional = noticeHistoryList.stream().filter(p -> !getBoolean(p.getEmail()) && getBoolean(p.getOneWeek())).findAny();
                }

                if (historyOptional.isPresent()) {
                    logger.info("already send the one week task email {}for company {}", email, company.getId());
                } else {
                    logger.info("will create new notice template one week {}", company.getId());
                    String content = planNoticeTemplate(company.getName(), email, "接下來這周", "next week");
                    EmailClient.getInstance().sendEmail(company.getEmail(), PLAN_EMAIL_TITLE, content);

                    //新建
                    logger.info("will create new notice history {}", company.getId());
                    NoticeHistory noticeHistoryNew = new NoticeHistory();
                    noticeHistoryNew.setCompanyId(company.getId());
                    noticeHistoryNew.setEmail(email);
                    noticeHistoryNew.setPlan(true);
                    noticeHistoryNew.setOneWeek(true);
                    commonService.directSave(noticeHistoryNew);
                }

                //如果已经超过了，一直需要退出
                return;
            }
        }

        {
            SendCount sendCount = getSendCount(periodMarketTaskList, Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)
                    .stream().map(p -> System.currentTimeMillis() + DateUtil.ONE_DAY * p).collect(Collectors.toList()));

            if (email) {
                addVipAndBirthdayEmailCount(company, sendCount, 14);
            }

            boolean isOver = false;

            if (email) {
                isOver = sendCount.getEmail() > 0 && canUsed < sendCount.getEmail();
            } else {
                isOver = sendCount.getSms() > 0 && canUsed < sendCount.getSms();
            }

            if (isOver) {
                //判断是否已经发送过了，没有发送则发送报告
                Optional<NoticeHistory> historyOptional = null;

                if (email) {
                    historyOptional = noticeHistoryList.stream().filter(p -> getBoolean(p.getEmail()) && getBoolean(p.getTwoWeek())).findAny();
                } else {
                    historyOptional = noticeHistoryList.stream().filter(p -> !getBoolean(p.getEmail()) && getBoolean(p.getTwoWeek())).findAny();
                }

                if (historyOptional.isPresent()) {
                    logger.info("already send the one week task for company {}", company.getId());
                } else {
                    logger.info("will create new notice template two week {}", company.getId());
                    String content = planNoticeTemplate(company.getName(), email, "接下來兩周", "next 2 weeks");
                    EmailClient.getInstance().sendEmail(company.getEmail(), PLAN_EMAIL_TITLE, content);

                    //新建
                    logger.info("will create new notice history {}", company.getId());
                    NoticeHistory noticeHistoryNew = new NoticeHistory();
                    noticeHistoryNew.setCompanyId(company.getId());
                    noticeHistoryNew.setEmail(email);
                    noticeHistoryNew.setPlan(true);
                    noticeHistoryNew.setTwoWeek(true);
                    commonService.directSave(noticeHistoryNew);
                }

                //如果已经超过了，一直需要退出
                return;
            }
        }

    }

    private void addVipAndBirthdayEmailCount(Company company, SendCount sendCount, int days) throws Exception {
        //生日邮件
        long endTime = DateUtil.endTimeInDay(System.currentTimeMillis() + DateUtil.ONE_DAY * days);
        customerTaskService.calBirthDayEmailCount(company, endTime, sendCount);
        //vip过期提醒
        Optional<VipRenewEmailTemplate> vipRenewEmailTemplateOptional = customerService.findVipRenewEmailTemplateByCompany(company.getId());
        if (vipRenewEmailTemplateOptional.isPresent() && getInt(vipRenewEmailTemplateOptional.get().getRemindDay()) > 0) {
            endTime = endTime - DateUtil.ONE_DAY * vipRenewEmailTemplateOptional.get().getRemindDay();
            customerTaskService.calVipRenewTaskEmailCount(company, endTime, sendCount);
        }
    }

    /**
     * 计算对应的计划配额，包括邮件和短信
     *
     * @param periodMarketTaskList
     * @param timeList
     * @return
     */
    private SendCount getSendCount(List<MarketTask> periodMarketTaskList, List<Long> timeList) {
        SendCount sendCount = new SendCount();
        timeList.stream().forEach(time -> {
            List<MarketTask> filterMarketTaskList = filterMarketTask(periodMarketTaskList, time);
            long email = sendCount.getEmail();
            sendCount.setEmail(email + filterMarketTaskList.stream().mapToLong(p -> getLong(p.getEmailUserCount())).sum());

            long sms = sendCount.getSms();
            sendCount.setSms(sms + filterMarketTaskList.stream().mapToLong(p -> customerService.calMarketTaskSmsCount(p) * getLong(p.getPhoneUserCount())).sum());
        });

        return sendCount;
    }

    /**
     * 过滤满足条件的时间任务
     *
     * @param marketTaskList
     * @param time
     * @return
     */
    private List<MarketTask> filterMarketTask(List<MarketTask> marketTaskList, long time) {
        return marketTaskList.stream().map(marketTask -> {
            boolean b = CustomerTaskService.getInstance().canAction(marketTask.getPeriodTimeConfig(), time);
            if (b) {
                try {
                    return (MarketTask) ClassUtil.clone(marketTask);
                } catch (Exception e) {
                    logger.error("e", e);
                    return null;
                }
            } else {
                return null;
            }
        }).filter(p -> p != null).collect(Collectors.toList());
    }

    /**
     * 获取发送内容
     *
     * @return
     */
    public String planNoticeTemplate(String userName, boolean email, String time_zh, String time_en)  throws  Exception{
        GlobalSetting globalSetting = globalService.getGlobalSetting();
        String address = globalSetting.getAddress();
        String city = globalSetting.getCity();
        String companyWebsite = globalSetting.getCompanyWebsite();
        String emailAddress = globalSetting.getEmailAddress();

        String type_zh = null;
        String type_en = null;

        if (email) {
            type_zh = "電郵";
            type_en = "Email";
        } else {
            type_zh = "短信";
            type_en = "SMS";
        }

        return String.format("<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "  <meta charset=\"UTF-8\">\n" +
                "  <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n" +
                "  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
                "  <style>\n" +
                "    *{margin: 0;padding: 0;box-sizing: border-box;font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Helvetica, Arial, \"Apple Color Emoji\", \"Segoe UI Emoji\", \"Segoe UI Symbol\", \"Liberation Sans\", \"PingFang SC\", \"Microsoft YaHei\", \"Hiragino Sans GB\", \"Wenquanyi Micro Hei\", \"WenQuanYi Zen Hei\", \"ST Heiti\", SimHei, SimSun, \"WenQuanYi Zen Hei Sharp\", sans-serif;}\n" +
                "    html, body{width: 100%%;height: 100%%;font-size: 20px;}\n" +
                "    .paper{width: 42rem;height: 59.4rem;display: flex;flex-wrap: wrap;align-items: center;flex-direction: column;margin: 0 auto;page-break-before:always;}\n" +
                "\n" +
                "    .logo{width: 100%%;height: 158px;display: flex;justify-content: flex-end;}\n" +
                "    .imgbox{width: 118px;height: 118px;margin: 20px;}\n" +
                "    .img{width: 100%%;height: 100%%;}\n" +
                "\n" +
                "    .content{width: 100%%;}\n" +
                "    .p{margin: 20px 0;}\n" +
                "\n" +
                "    .foot{display: flex;align-items: center;flex-direction: column;margin-top: 80px;}\n" +
                "    .text1{color: #7f7f7f;font-size: 0.8rem;margin: 4px 0;}\n" +
                "    .text2{color: #4793A3;font-size: 0.8rem;margin: 4px 0;}\n" +
                "    \n" +
                "    @media print {\n" +
                "      .print_hide {display: none;}\n" +
                "      @page { size: auto; /* auto is the initial value */ margin: 0mm; /* this affects the margin in the printer settings */ }\n" +
                "    }\n" +
                "  </style>\n" +
                "  <title>配额提醒</title>\n" +
                "</head>\n" +
                "<body>\n" +
                "  <div class=\"paper\">\n" +
                "    <div class=\"logo\">\n" +
                "      <div class=\"imgbox\">\n" +
                "        <img src=\"%s\" alt=\"logo\" class=\"img\">\n" +
                "      </div>\n" +
                "    </div>\n" +
                "    <div class=\"content\">\n" +
                "      <p class=\"p\">Hi %s,</p>\n" +
                "      <p class=\"p\">您好%s，</p>\n" +
                "      <p class=\"p\">Your remaining %s credits for marketing are not enough for %s. Please contact DoLA to top up your credits. </p>\n" +
                "      <p class=\"p\">您的%s營銷配額不足，這將會影響到您%s的營銷計劃。請連絡DoLA充值配額。</p>\n" +
                "      <p class=\"p\">If you are not using DoLA, please ignore this email. </p>\n" +
                "      <p class=\"p\">如果您并沒有注冊DoLA，請忽略這封電郵。</p>\n" +
                "    </div>\n" +
                "    <div class=\"foot\">\n" +
                "      <p class=\"text1\">"+address+"</p>\n" +
                "      <p class=\"text1\">"+city+"</p>\n" +
                "      <p class=\"text2\">"+emailAddress+" | "+companyWebsite+"</p>\n" +
                "    </div>\n" +
                "  </div>\n" +
                "</body>\n" +
                "</html>", PlatService.getInstance().getLogoUrl(), userName, userName, type_en, time_en, type_zh, time_zh);
    }

    /**
     * 获取发送内容
     *
     * @return
     */
    public String unplannedNoticeTemplate(String userName, boolean email, String time_zh, String time_en)  throws Exception{
        GlobalSetting globalSetting = globalService.getGlobalSetting();
        String address = globalSetting.getAddress();
        String city = globalSetting.getCity();
        String companyWebsite = globalSetting.getCompanyWebsite();
        String emailAddress = globalSetting.getEmailAddress();

        String type_zh = null;
        String type_en = null;

        if (email) {
            type_zh = "電郵";
            type_en = "Email";
        } else {
            type_zh = "短信";
            type_en = "SMS";
        }

        return String.format("<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "  <meta charset=\"UTF-8\">\n" +
                "  <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n" +
                "  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
                "  <style>\n" +
                "    *{margin: 0;padding: 0;box-sizing: border-box;font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Helvetica, Arial, \"Apple Color Emoji\", \"Segoe UI Emoji\", \"Segoe UI Symbol\", \"Liberation Sans\", \"PingFang SC\", \"Microsoft YaHei\", \"Hiragino Sans GB\", \"Wenquanyi Micro Hei\", \"WenQuanYi Zen Hei\", \"ST Heiti\", SimHei, SimSun, \"WenQuanYi Zen Hei Sharp\", sans-serif;}\n" +
                "    html, body{width: 100%%;height: 100%%;font-size: 20px;}\n" +
                "    .paper{width: 42rem;height: 59.4rem;display: flex;flex-wrap: wrap;align-items: center;flex-direction: column;margin: 0 auto;page-break-before:always;}\n" +
                "\n" +
                "    .logo{width: 100%%;height: 158px;display: flex;justify-content: flex-end;}\n" +
                "    .imgbox{width: 118px;height: 118px;margin: 20px;}\n" +
                "    .img{width: 100%%;height: 100%%;}\n" +
                "\n" +
                "    .content{width: 100%%;}\n" +
                "    .p{margin: 20px 0;}\n" +
                "\n" +
                "    .foot{display: flex;align-items: center;flex-direction: column;margin-top: 80px;}\n" +
                "    .text1{color: #7f7f7f;font-size: 0.8rem;margin: 4px 0;}\n" +
                "    .text2{color: #4793A3;font-size: 0.8rem;margin: 4px 0;}\n" +
                "    \n" +
                "    @media print {\n" +
                "      .print_hide {display: none;}\n" +
                "      @page { size: auto; /* auto is the initial value */ margin: 0mm; /* this affects the margin in the printer settings */ }\n" +
                "    }\n" +
                "  </style>\n" +
                "  <title>配额提醒</title>\n" +
                "</head>\n" +
                "<body>\n" +
                "  <div class=\"paper\">\n" +
                "    <div class=\"logo\">\n" +
                "      <div class=\"imgbox\">\n" +
                "        <img src=\"%s\" alt=\"logo\" class=\"img\">\n" +
                "      </div>\n" +
                "    </div>\n" +
                "    <div class=\"content\">\n" +
                "      <p class=\"p\">Hi %s,</p>\n" +
                "      <p class=\"p\">您好%s，</p>\n" +
                "      <p class=\"p\">Your remaining %s credits for verification services %s. Please contact DoLA to top up your credits.  </p>\n" +
                "      <p class=\"p\">您的%s驗證碼配額不足，這將會影響到您%s的會員驗證。請連絡DoLA充值配額。</p>\n" +
                "      <p class=\"p\">If you are not using DoLA, please ignore this email. </p>\n" +
                "      <p class=\"p\">如果您并沒有注冊DoLA，請忽略這封電郵。</p>\n" +
                "    </div>\n" +
                "    <div class=\"foot\">\n" +
                "      <p class=\"text1\">"+address+"</p>\n" +
                "      <p class=\"text1\">"+city+"</p>\n" +
                "      <p class=\"text2\">"+emailAddress+" | "+companyWebsite+"</p>\n" +
                "    </div>\n" +
                "  </div>\n" +
                "</body>\n" +
                "</html>", PlatService.getInstance().getLogoUrl(), userName, userName, type_en, time_en, type_zh, time_zh);
    }


}
